package com.dikeleakagedetection.myapplication.ui.dataMonitor

import android.app.Activity
import android.content.DialogInterface
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.MediaStore
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.content.FileProvider
import androidx.fragment.app.DialogFragment
import com.dikeleakagedetection.myapplication.DikeLeakageDetectionApp
import com.dikeleakagedetection.myapplication.databinding.DlgNewTabletBinding
import com.dikeleakagedetection.myapplication.utils.rotateRequired
import java.io.File
import java.text.SimpleDateFormat
import java.util.*

class NewTabletDialogFragment : DialogFragment() {

    private lateinit var binding: DlgNewTabletBinding

    private var clickCallBack: ClickCallBack? = null
    private val takePhoto = 1
    private lateinit var imageUri: Uri
    private lateinit var outputImage: File
    private lateinit var tempBitmap: Bitmap

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        binding = DlgNewTabletBinding.inflate(inflater, container, false)
        dialog!!.setCanceledOnTouchOutside(false)
        initWindow()
        initView()
        return binding.root
    }

    private fun initView() {

        val nowDate = Date()
        val sft = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
        binding.tvDateDlgNewTablet.text = sft.format(nowDate).toString()

        //点击图片拍照
        binding.imgPhotoDlgNewTablet.setOnClickListener {
            //创建File对象，用于储存拍照后的图片
            outputImage = File(
                //MyApplication.context.getExternalFilesDir(null),
                DikeLeakageDetectionApp.context.externalCacheDir,
                "output_image.jpg"
            )
            if (outputImage.exists()) {
                outputImage.delete()
            }
            outputImage.createNewFile()
            imageUri = getImageUri(outputImage)

            //启动相机程序
            val intent = Intent("android.media.action.IMAGE_CAPTURE").apply {
                putExtra(MediaStore.EXTRA_OUTPUT, imageUri)

            }
            startActivityForResult(intent, takePhoto)
        }

        //点击确认
        binding.tvConfirmDigSelectTablet.setOnClickListener {
            val date: String = binding.tvDateDlgNewTablet.text.toString()
            val place: String = binding.etSetPlaceDlgNewTablet.text.toString()
            val length: Double = binding.etSetLengthDlgNewTablet.text.toString().toDouble()
            val width: Double = binding.etSetWidthDlgNewTablet.text.toString().toDouble()
            clickCallBack?.clickConfirm(date, place, length, width, tempBitmap)
            dismiss()
        }

        //点击取消
        binding.tvCancelDigSelectTablet.setOnClickListener {
            dismiss()
        }

    }

    private fun getImageUri(outputImage: File) = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        FileProvider.getUriForFile(
            requireContext(),
            "com.dikeleakagedetection.myapplication.fileprovider",
            outputImage
        )
    } else {
        Uri.fromFile(outputImage)
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        when (requestCode) {
            takePhoto -> {
                if (resultCode == Activity.RESULT_OK) {
                    //将拍摄的照片显示出来
                    val bitmap = BitmapFactory.decodeStream(
                        requireContext().contentResolver.openInputStream(imageUri)
                    )
                    tempBitmap = rotateRequired(bitmap, outputImage)
                    binding.imgPhotoDlgNewTablet.setImageBitmap(tempBitmap)
                }
            }
        }
    }

    private fun initWindow() {
        //初始化window相关
        val window = dialog?.window //获取window对象
        window?.apply {
            setBackgroundDrawable(ColorDrawable(Color.WHITE))//设备背景为透明（默认白色）
            attributes.width = 1200
            attributes.gravity = Gravity.CENTER

        }

    }

    fun setClickCallBack(clickCallBack: ClickCallBack) {
        this.clickCallBack = clickCallBack
    }

    interface ClickCallBack {
        fun clickConfirm(date: String, place: String, length: Double, width: Double, tempBitmap: Bitmap)
    }

}